import { createSlice } from '@reduxjs/toolkit';

export const slice = createSlice({
  name: 'counter',
  initialState: {
    value: 0,
    userInfo: {
      name: '蒙奇·D·路飞',
      age: 18,
    },
  },
  reducers: {
    changeUserInfo: (state, { payload }) => {
      console.log(payload);
      state.userInfo = {
        ...state.userInfo,
        ...payload,
      };
    },
    increment: (state) => {
      state.value += 1;
    },
    decrement: (state) => {
      state.value -= 1;
    },
    incrementByAmount: (state, action) => {
      state.value += action.payload;
    },
  },
});

export const { increment, decrement, incrementByAmount, changeUserInfo } = slice.actions;

export const incrementAsync = (amount: any) => (dispatch: any) => {
  setTimeout(() => {
    dispatch(incrementByAmount(amount));
  }, 1000);
};

export const selectCount = (state: any) => state.counter.value;
export const userInfoR = (state: any) => state.counter.userInfo;
export default slice.reducer;
